package org.tgcloud.group.web.controller.manager;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.tgcloud.group.core.APPResultMessage;
import org.tgcloud.group.core.StringUtil;
import org.tgcloud.group.core.custom.Permissions;
import org.tgcloud.group.core.session.Session;
import org.tgcloud.group.entity.MjOrder;
import org.tgcloud.group.repository.MjOrderMapper;
import org.tgcloud.group.service.app.OrderService;
import org.tgcloud.group.service.manager.OrderManagerService;
import org.tgcloud.group.web.controller.dto.order.ManagerOrderDTO;
import org.tgcloud.group.web.controller.req.order.FlagshipStoreDataReq;
import org.tgcloud.group.web.controller.req.order.OrderIdReq;
import org.tgcloud.group.web.controller.req.order.OrderSureCheckReq;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author: zhy
 * @create: 2023-08-14 16:42
 * @description: 订单相关接口
 */
@Api(tags = "订单管理相关接口")
@RestController
@RequestMapping("/manager/pc/user")
@EnableAutoConfiguration
public class OrderManagerController extends ManageAPPBaseController{

    @Autowired
    private OrderManagerService orderManagerService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private MjOrderMapper orderMapper;


    @Permissions("order:add")
    @ApiOperation(value = "发布订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/sendOrder", method = RequestMethod.POST)
    public APPResultMessage doSendOrder(@ModelAttribute("session") Session session,
                                        @RequestParam(required = false) String cateGoryIds,
                                        @RequestParam(required = false) String brands,
                                        @RequestParam String goods,
                                        @RequestParam Integer projectId,
                                        @RequestParam(required = false) String projectDemand){
        return orderManagerService.doSendOrder(session.getUserId(), session.getUserType(),null,cateGoryIds,brands,projectId,goods, projectDemand);
    }



    @ApiOperation(value = "导入excel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public APPResultMessage doImportExcel(@RequestPart("file") MultipartFile file,
                                          @ModelAttribute("session") Session session,
                                          @RequestParam(required = false) Integer projectId){
        return orderManagerService.doImportExcel(file, session.getUserId(),projectId);
    }




    @Permissions("order:editBrand")
    @ApiOperation(value = "订单-修改品类、品牌")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/updateOrderBrand", method = RequestMethod.POST)
    public APPResultMessage doUpdateOrderBrand(@ModelAttribute("session") Session session,
                                        @RequestParam Integer orderId,
                                        @RequestParam(required = false) String cateGoryIds,
                                        @RequestParam(required = false) String brands){
        return orderManagerService.doUpdateOrderBrand(session.getUserId(),orderId,cateGoryIds,brands);
    }

    @ApiOperation(value = "订单-下载核价模板")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/exportOrder", method = RequestMethod.POST)
    public void exportOrder(@ModelAttribute("session") Session session,
                                               @RequestParam Integer projectId,
                                        HttpServletResponse response){
        orderManagerService.exportOrder(projectId,response);
    }

    @ApiOperation(value = "订单-上传核价信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/importOrder", method = RequestMethod.POST)
    public APPResultMessage importOrder(@RequestPart("file") MultipartFile file,
                                        @ModelAttribute("session") Session session,
                                        @RequestParam(required = false) Integer projectId) throws IOException {
        return orderManagerService.importOrder(file,session.getUserId(),projectId);
    }




    @Permissions("order:push")
    @ApiOperation(value = "订单-推送订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/pushOrderMsg", method = RequestMethod.POST)
    public APPResultMessage doPushOrderMsg(@ModelAttribute("session") Session session,
                                               @RequestParam Integer orderId,
                                           @RequestParam String pushUserIds,
                                           @RequestParam(required = false) String resourcesRemark){
        if (StringUtil.isBlank(pushUserIds)){
            return APPResultMessage.MISS_PARAMETER();
        }
        return orderManagerService.doPushOrderMsg(session.getUserId(),orderId, pushUserIds, resourcesRemark);
    }



    @ApiOperation(value = "订单-推送资源要求")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/pushOrderResourcesRemark", method = RequestMethod.POST)
    public APPResultMessage doPushOrderResourcesRemark(@ModelAttribute("session") Session session,
                                           @RequestParam Integer orderId,
                                           @RequestParam(required = false) String resourcesRemark){
        return orderManagerService.doPushOrderResourcesRemark(session.getUserId(),orderId, resourcesRemark);
    }


    @Permissions("order:rePush")
    @ApiOperation(value = "订单-重新推送订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/rePushOrderMsg", method = RequestMethod.POST)
    public APPResultMessage doRePushOrderMsg(@ModelAttribute("session") Session session,
                                           @RequestParam Integer orderId,
                                           @RequestParam String pushUserIds){
        if (StringUtil.isBlank(pushUserIds)){
            return APPResultMessage.MISS_PARAMETER();
        }
        return orderManagerService.doRePushOrderMsg(session.getUserId(),orderId, pushUserIds);
    }


    @Permissions("order:edit")
    @ApiOperation(value = "发布订单-修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/sendOrderUpdate", method = RequestMethod.POST)
    public APPResultMessage doSendOrderUpdate(@ModelAttribute("session") Session session,
                                              @RequestParam Integer orderId,
                                              @RequestParam String goods,
                                              @RequestParam Integer projectId,
                                              @RequestParam(required = false) String cateGoryIds,
                                              @RequestParam(required = false) String brands) throws Exception{
        return orderManagerService.doSendOrderUpdate(session.getUserId(),null,cateGoryIds,brands,orderId,goods,projectId);
    }



    @Permissions("order:view")
    @ApiOperation(value = "订单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string"),
    })
    @ResponseBody
    @RequestMapping(value = "/orderList", method = RequestMethod.POST)
    public APPResultMessage<Object, ManagerOrderDTO> getOrderList(@ModelAttribute("session") Session session,
                                                                  @RequestParam(required = false) Integer pageNum,
                                                                  @RequestParam(required = false) Integer pageSize,
                                                                  @RequestParam(required = false) String keyword,
                                                                  @RequestParam(required = false) Long startTime,
                                                                  @RequestParam(required = false) Long endTime,
                                                                  @RequestParam(required = false) Short status,
                                                                  @RequestParam(required = false) Integer projectId,
                                                                  @RequestParam(required = false) Integer executionProgressId,
                                                                  @RequestParam(required = false) Integer arrivalProgressId,
                                                                  @RequestParam(required = false) Integer arrivalWarehouseId,
                                                                  @RequestParam(required = false) Short isDiscount,
                                                                  @RequestParam(required = false) Integer permissionId,
                                                                  @RequestParam(required = false) Integer businessId,
                                                                  @RequestParam(required = false) String areaId,
                                                                  @RequestParam(required = false) String cateIds,
                                                                  @RequestParam(required = false) BigDecimal startPrice,
                                                                  @RequestParam(required = false) BigDecimal endPrice,
                                                                  @RequestParam(required = false) Short statusType,
                                                                  @RequestParam(required = false) String statuses,
                                                                  @RequestParam(required = false) Short fileType,
                                                                  @RequestParam(required = false) Short isTimeOut,
                                                                  @RequestParam(required = false) Integer orderGo,
                                                                  @RequestParam(required = false) Long pushSureCheckStartTime,
                                                                  @RequestParam(required = false) Long pushSureCheckEndTime,
                                                                  @RequestParam(required = false) Short showSubOrderType,
                                                                  @RequestParam(required = false) Short hasCommitFinalPrice) {
        return orderManagerService.doGetOrderList(pageNum,pageSize,keyword,startTime == null ? null : new Date(startTime),
                endTime == null ? null : new Date(endTime), status, session.getUserId(), session.getComId(), projectId,executionProgressId,
                arrivalProgressId,arrivalWarehouseId,isDiscount,permissionId,businessId,areaId,cateIds, startPrice, endPrice,
                statuses, statusType,fileType,isTimeOut,orderGo, pushSureCheckStartTime, pushSureCheckEndTime, showSubOrderType);
    }


    @Permissions("order:cancel")
    @ApiOperation(value = "订单-作废订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/cancelOrder", method = RequestMethod.POST)
    public APPResultMessage doCancelOrder(@ModelAttribute("session") Session session,
                                           @RequestParam String orderIds){
        if (StringUtil.isBlank(orderIds)){
            return APPResultMessage.MISS_PARAMETER();
        }
        return orderManagerService.doCancelOrder(session.getUserId(), session.getUserType(), orderIds);
    }


    @Permissions("order:del")
    @ApiOperation(value = "订单-删除订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/delOrder", method = RequestMethod.POST)
    public APPResultMessage doDelOrder(@ModelAttribute("session") Session session,
                                          @RequestParam String orderIds){
        if (StringUtil.isBlank(orderIds)){
            return APPResultMessage.MISS_PARAMETER();
        }
        return orderManagerService.doDelOrder(session.getUserId(),orderIds);
    }



    @Permissions("order:view")
    @ApiOperation(value = "订单-查看订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/getOrderMsg", method = RequestMethod.POST)
    public APPResultMessage getOrderMsg(@ModelAttribute("session") Session session,
                                       @RequestParam(required = false) Integer orderId,
                                        @RequestParam(required = false) Integer projectId){

        if(ObjectUtil.isNull(orderId) && ObjectUtil.isNotNull(projectId)){
            MjOrder mjOrder = orderMapper.selectOne(
                    new LambdaQueryWrapper<MjOrder>()
                            .eq(MjOrder::getProjectId, projectId)
                            .notIn(MjOrder::getStatus, 9, 10, 11)
                            .isNull(MjOrder::getParentId)
            );
            orderId = mjOrder.getId();
        }
        return orderManagerService.getOrderMsg(session.getUserId(),orderId, session.getComId());
    }



    @Permissions("order:sureCheckOrder")
    @ApiOperation(value = "订单-确定核价等待中的订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/sureCheckOrder", method = RequestMethod.POST)
    public APPResultMessage doSureCheckOrder(@ModelAttribute("session") Session session,
                                       @RequestParam String orderIds){
        if (StringUtil.isBlank(orderIds)){
            return APPResultMessage.MISS_PARAMETER();
        }
        return orderManagerService.doSureCheckOrder(session.getUserId(),orderIds);
    }



    @Permissions("order:adjust")
    @ApiOperation(value = "调整订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/adjustOrder", method = RequestMethod.POST)
    public APPResultMessage doAdjustOrder(@ModelAttribute("session") Session session,
                                          @RequestParam String goods,
                                          @RequestParam(required = false) Integer biddingUserId,
                                          @RequestParam Integer orderId){
        return orderManagerService.doAdjustOrder(session.getUserId(),goods,orderId, biddingUserId);
    }


    @Permissions("order:view")
    @ApiOperation(value = "获取订单的最终的商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/getOrderGoodList", method = RequestMethod.POST)
    public APPResultMessage getOrderGoodList(@ModelAttribute("session") Session session,
                                             @RequestParam Integer orderId){
        return orderManagerService.getOrderGoodList(session.getUserId(),orderId);
    }


    @Permissions("order:editCost,order:editRealPrice")
    @ApiOperation(value = "修改订单成本数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/doEditOrderCost", method = RequestMethod.POST)
    public APPResultMessage doEditOrderCost(@ModelAttribute("session") Session session,
                                            @RequestParam Integer orderId,
                                            @RequestParam(required = false) BigDecimal innerPrice,
                                            @RequestParam(required = false) BigDecimal blindRealPrice,
                                            @RequestParam(required = false) BigDecimal saleRealPrice,
                                            @RequestParam(required = false) BigDecimal projectRealPrice,
                                            @RequestParam(required = false) Integer orderGo,
                                            @RequestParam(required = false) BigDecimal expectPrice,
                                            @RequestParam(required = false) BigDecimal estimatedSelfMediaCost,
                                            @RequestParam(required = false) BigDecimal estimatedExternalMediaCost,
                                            @RequestParam(required = false) BigDecimal actualSelfMediaCost,
                                            @RequestParam(required = false) BigDecimal actualExternalMediaCost
    ){
        return orderManagerService.doEditOrderCost(session.getUserId(),orderId, innerPrice, blindRealPrice,
                saleRealPrice, projectRealPrice,orderGo,expectPrice,
                estimatedSelfMediaCost, estimatedExternalMediaCost, actualSelfMediaCost, actualExternalMediaCost);
    }


    @Permissions("order:addTimeOutRemark")
    @ApiOperation(value = "商务超时订单说明")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/doAddTimeOutRemark", method = RequestMethod.POST)
    public APPResultMessage doAddTimeOutRemark(@ModelAttribute("session") Session session,
                                            @RequestParam Integer orderId,

                                            @RequestParam(required = false) String content
                                            ){
        return orderManagerService.doAddTimeOutRemark(session.getUserId(),orderId,content);
    }

    @Permissions("order:splitOrder")
    @ApiOperation(value = "订单拆分-拆单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/doSplitOrder", method = RequestMethod.POST)
    public APPResultMessage doSplitOrder(@ModelAttribute("session") Session session,
                                               @RequestParam Integer parentId,
                                               @RequestParam String orderStr,
                                               @RequestParam Integer fileType,
                                               @RequestParam String useTypeStr
    ){
        return orderManagerService.doSplitOrder(session.getUserId(),parentId,orderStr,fileType,useTypeStr);
    }

//    @Permissions("order:selectChild")
    @ApiOperation(value = "查找子订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/selectChild", method = RequestMethod.POST)
    public APPResultMessage selectChild(@ModelAttribute("session") Session session,
                                         @RequestParam Integer parentId
    ){
        return orderManagerService.selectChild(session.getUserId(),parentId);
    }

    @Permissions("order:deleteChildOrder")
    @ApiOperation(value = "删除子表单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/deleteChild", method = RequestMethod.POST)
    public APPResultMessage deleteChild(@ModelAttribute("session") Session session,
                                        @RequestParam Integer parentId
    ){
        return orderManagerService.deleteChild(session.getUserId(),parentId);
    }

    @Permissions("order:confirmOrderUse")
    @ApiOperation(value = "选择订单用处")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/confirmOrderUse", method = RequestMethod.POST)
    public APPResultMessage confirmOrderUse(@ModelAttribute("session") Session session,
                                            @RequestParam Integer orderId,
                                            @RequestParam Integer useType,
                                            @RequestParam BigDecimal expectPrice
    ){
        return orderManagerService.confirmOrderUse(session.getUserId(),orderId,useType,expectPrice);
    }



    @Permissions("order:editCost")
    @ApiOperation(value = "订单拆分-竞价后拆单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/doSplitOrderAfterBidding", method = RequestMethod.POST)
    public APPResultMessage doSplitOrderAfterBidding(@ModelAttribute("session") Session session,
                                         @RequestParam Integer parentId,
                                         @RequestParam String orderStr,
                                         @RequestParam Integer fileType,
                                         @RequestParam String useTypeStr){
        return orderManagerService.doSplitOrderAfterBidding(session.getUserId(),parentId,orderStr,fileType,useTypeStr);
    }



    @Permissions("order:setRate")
    @ApiOperation(value = "订单-评级")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/doSetOrderRate", method = RequestMethod.POST)
    public APPResultMessage doSetOrderRate(@ModelAttribute("session") Session session,
                                           @RequestParam Integer orderId,
                                           @RequestParam Integer rateId){
        return orderManagerService.doSetOrderRate(session.getUserId(), session.getUserType(),orderId,rateId);
    }

    @Permissions("order:setRate")
    @ApiOperation(value = "订单评级记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/getSetOrderRateRecordList", method = RequestMethod.POST)
    public APPResultMessage getSetOrderRateRecordList(@ModelAttribute("session") Session session,
                                                      @RequestParam Integer orderId){
        return orderManagerService.getSetOrderRateRecordList(orderId);
    }

    @Permissions("order:skipBidding")
    @ApiOperation(value = "订单跳过竞价流程")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/doSkipBidding", method = RequestMethod.POST)
    public APPResultMessage doSkipBidding(@RequestParam Integer orderId,
                                          @ModelAttribute("session") Session session,
                                          @RequestParam Integer chooseOrderId){
        return orderManagerService.doSkipBidding(orderId, session.getUserId(), chooseOrderId);
    }


    @ApiOperation(value = "查询展示该项目下的其他已竞价的订单（包括子订单）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string")
    })
    @ResponseBody
    @RequestMapping(value = "/getOtherHasBiddingOrderList", method = RequestMethod.POST)
    public APPResultMessage getOtherHasBiddingOrderList(@RequestParam Integer orderId){
        return orderManagerService.getOtherHasBiddingOrderList(orderId);
    }


    @ApiOperation(value = "订单-开拓者确认渠道核价")
    @ApiImplicitParams({
    })
    @ResponseBody
    @PostMapping(value = "/sureChannelCheckPrice")
    public APPResultMessage<Object, List> doSureChannelCheckPrice(@ModelAttribute("session")Session session,
                                                                  @RequestBody OrderSureCheckReq req) {
        return orderService.doSureChannelCheckPrice(session.getUserId(), session.getUserType(),req);
    }



    @Permissions("order:submitFlagshipStoreData")
    @ApiOperation(value = "订单-填写旗舰店数据")
    @ApiImplicitParams({
    })
    @ResponseBody
    @PostMapping(value = "/submitFlagshipStoreData")
    public APPResultMessage doSubmitFlagshipStoreData(@ModelAttribute("session")Session session,
                                                      @RequestBody FlagshipStoreDataReq req) {
        return orderManagerService.doSubmitFlagshipStoreData(req, session.getUserId(), session.getUserType());
    }


    @ApiOperation(value = "订单-查看商品列表")
    @ApiImplicitParams({
    })
    @ResponseBody
    @PostMapping(value = "/viewGoodsList")
    public APPResultMessage viewGoodsList(@ModelAttribute("session")Session session,
                                          @RequestBody OrderIdReq req) {
        return orderManagerService.viewGoodsList(req);
    }

}
